<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" plain @click="addroledialog">添加管理员</el-button>
    </div>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='昵称'>
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='账号'>
        <template slot-scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='手机'>
        <template slot-scope="scope">
          {{scope.row.phone}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='邮箱'>
        <template slot-scope="scope">
          {{scope.row.email}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="bianji(scope.row,scope.$index)" plain>编辑</el-button>
          <el-button type="danger" size="mini" @click="shanchu(scope.row, scope.$index)" plain>删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--编辑表单弹窗-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="formsrules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 470px; margin-left:50px;'>
        <el-form-item v-if="dialogStatus=='create'" label="账号：" prop="username">
          <el-input type="text" v-model="temp.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'" label="密码：" prop="password">
          <input type="password" style="display:none">
          <el-input type="password" v-model="temp.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称：">
          <el-input type="text" v-model="temp.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话：" prop="phone">
          <el-input type="tel" v-model="temp.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input type="email" v-model="temp.email" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addrole">确 定</el-button>
        <el-button v-else type="primary" @click="sureEdit">确 定</el-button>
      </div>
    </el-dialog>
    <!--编辑表单弹窗END-->

    <!--分页-->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.page" :page-sizes="[10,20,30,50]"
                     :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </div>
    <!--分页END-->
  </div>
</template>

<script>
  import { getList, addroles, sureEdit, shanchu } from '@/api/system/adminList'

  export default {
    data() {
      const validatePass = (rule, value, callback) => {
        if (value.length < 8) {
          callback(new Error('密码不能小于8位，请使用字母、数字排列组合'))
        } else {
          callback()
        }
      }
      const checkusername = (rule, value, callback) => {
        const han = /^[\u4e00-\u9fa5]+$/
        if (!value) {
          return callback(new Error('请输入账号'))
        } else if (han.test(value)) {
          return callback(new Error('不允许输入汉字'))
        } else {
          callback()
        }
      }
      const checkPhone = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入手机号码'))
        }
        if (value.length < 11) {
          return callback(new Error('请填写正确的号码'))
        } else {
          callback()
        }
      }
      return {
        list: null,
        listLoading: true,
        total: null,
        listQuery: {
          id: undefined,
          name: '',
          defaultarea: [],
          area: [],
          type: ''
        },
        temp: {
          id: undefined,
          name: '',
          username: '',
          password: '',
          phone: '',
          email: ''
        },
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogFormVisible: false,
        formsrules: {
          username: [
            { validator: checkusername, trigger: 'blur' }
          ],
          password: [
            { required: true, trigger: 'blur', validator: validatePass }
          ],
          phone: [{ required: true, trigger: 'blur', validator: checkPhone }],
          email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
        }
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          normal: '正常',
          disble: '停止'
        }
        return statusMap[status]
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      // 获取列表
      fetchData() {
        this.listLoading = true
        getList(this.listQuery).then(response => {
          this.list = response.data.content
          this.total = response.data.totalElements
          this.listQuery.size = response.data.size
          this.listLoading = false
        })
      },
      addroledialog() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: '',
          username: '',
          password: '',
          phone: '',
          email: ''
        }
      },
      addrole() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addroles(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              location.reload()
            })
          }
        })
      },
      bianji(row) {
        this.temp = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      sureEdit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const temData = Object.assign({}, this.temp)
            sureEdit(temData).then(response => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      shanchu(row) {
        this.$confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          shanchu(row.uuid).then(() => {
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.fetchData()
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .filter-container{
    padding-bottom: 10px;
  }
  .area-select .el-select{
    margin-left: 0;
  }
</style>
